package com.accesshollywood.grfxOrdering.Dialogs;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.EnumSet;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.JTextComponent;
import javax.xml.soap.Text;

import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.language.Soundex;
import org.jdesktop.swingx.HorizontalLayout;
import org.jdesktop.swingx.VerticalLayout;
import org.jdesktop.swingx.autocomplete.AbstractAutoCompleteAdaptor;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import org.jdesktop.swingx.autocomplete.AutoCompleteDocument;

import com.accesshollywood.SQL.GFXSQL;
import com.accesshollywood.components.BasicPopupMenu;
import com.accesshollywood.components.EditableListWithPopup;
import com.accesshollywood.components.EditableListWithPopup.EditableListModel;
import com.accesshollywood.components.IconUtil;
import com.accesshollywood.grfxOrdering.GRFXOrdersMain;
import com.accesshollywood.grfxOrdering.basics.Users;
import com.accesshollywood.indexables.PreApprovedText;
import com.accesshollywood.prefs.Prefs;
import com.accesshollywood.printing.PrintGrfxOrder;

public class PreApprovedDialog extends AbstractCustomDialog {

	private static JPanel								contentPanel;
	// public static EditableOneColumnTable masterList;
	public static EditableListWithPopup					masterList;
	public JPopupMenu									popup;
	public JTextField									searchText;
	private static JTextField							textField	= new JTextField();
	// private JLabel lblResearcher;
	// private JLabel lblDateApproved;
	// private JLabel lblReference;
	private JTextArea									notesArea;
	private JButton										btnUpdateNotes;
	private static EditableListModel<PreApprovedText>	model		= new EditableListModel<PreApprovedText>();
	private boolean										editable	= false;
	private static PreApprovedAutoCompleteAdaptor		adaptor;
	private static PreApprovedAutoCompleteDocument		doc;

	public PreApprovedDialog(Window w, ModalityType modality) {
		super(w, modality);
		createDialog();

		setupAutoCorrect();
	}

	public static void refresh(boolean fromSQL) {
		if (fromSQL) {
			model.create(GFXSQL.getPreApprovalList(), Users.researchUsers.toArrayList());
		}
		GRFXOrdersMain.preApprovedDictionary.refresh();
		AutoCompleteDecorator.decorate(textField, GRFXOrdersMain.preApprovedDictionary.toWordList(), false);
		// if (doc != null && adaptor != null) {
		// AutoCompleteDecorator.decorate(textField, doc, adaptor);
		// }
		masterList.revalidate();
		masterList.repaint();
	}

	public void setupAutoCorrect() {
		adaptor = new PreApprovedAutoCompleteAdaptor(textField, GRFXOrdersMain.preApprovedDictionary.toWordList());
		doc = new PreApprovedAutoCompleteDocument(adaptor, false);
		AutoCompleteDecorator.decorate(textField, doc, adaptor);
	}

	public void createDialog() {
		setBounds(100, 100, 450, 390);
		contentPanel = (JPanel) getContentPane();
		contentPanel.setLayout(new VerticalLayout());

		JPanel listPanel = new JPanel();
		listPanel.setLayout(new VerticalLayout());

		JPanel searchPanel = new JPanel();
		searchPanel.setLayout(new HorizontalLayout());
		listPanel.add(searchPanel);

		searchPanel.add(new JLabel("  Text: "));

		textField = new JTextField();
		textField.setPreferredSize(new Dimension(320, 20));
		searchPanel.add(textField);
		// textField.getDocument().addDocumentListener(new SearchTypeListener());

		JButton btnAddEntry = new JButton("Add");
		btnAddEntry.setAlignmentX(Component.RIGHT_ALIGNMENT);
		searchPanel.add(btnAddEntry);
		btnAddEntry.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				addEntry();
			}
		});

		ImageIcon printIcon = IconUtil.createImageIcon("res/icons/print.jpg", "Print");
		JLabel btn_print;
		btn_print = new JLabel(printIcon);
		btn_print.setPreferredSize(new Dimension(26, 20));
		btn_print.setMinimumSize(new Dimension(26, 20));
		btn_print.setMaximumSize(new Dimension(26, 20));
		btn_print.addMouseListener(new PrintClickListener());
		searchPanel.add(btn_print);

		JPanel masterListPanel = new JPanel();
		masterListPanel.setBorder(new TitledBorder(null, "MasterList:", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		masterListPanel.setLayout(new VerticalLayout());

		listPanel.add(masterListPanel);
		masterList = new EditableListWithPopup(model, Prefs.PixelSize.preApprovedList.get(), Text.class);
		masterList.setRefreshMe(PreApprovedDialog.class);
		model.create(GFXSQL.getPreApprovalList(), Users.researchUsers.toArrayList());

		JScrollPane masterListScroller = new JScrollPane(masterList);
		masterList.setPreferredSize(new Dimension(300, 150));
		masterList.getSelectionModel().addListSelectionListener(new MasterListSelectionListener());

		AutoCompleteDecorator.decorate(textField, GRFXOrdersMain.preApprovedDictionary.toWordList(), false);

		/*
		 * masterList = new EditableOneColumnTable(masterListPanel, GRFXOrdersMain.preApprovedDictionary, Prefs.PixelSize.preApprovedList.get(), true);
		 * masterList.setRefreshMe(PreApprovedDialog.class);
		 * masterList.getModel().create(GFXSQL.getPreApprovalList(), Users.researchUsers.toArrayList());
		 * AutoCompleteDecorator.decorate(textField, GRFXOrdersMain.preApprovedDictionary.toWordList(), false);
		 * JScrollPane masterListScroller = new JScrollPane(masterList);
		 * masterList.setPreferredSize(new Dimension(300, 150));
		 * masterList.getSelectionModel().addListSelectionListener(new MasterListSelectionListener());
		 */
		setupPopup();

		masterListScroller.setPreferredSize(new Dimension(300, 150));

		masterListPanel.add(masterListScroller);

		JPanel infoPanel = new JPanel();
		infoPanel.setLayout(new VerticalLayout());

		// lblResearcher = new JLabel("Researcher:");
		// infoPanel.add(lblResearcher);

		// lblDateApproved = new JLabel("Date Approved:");
		// infoPanel.add(lblDateApproved);

		// lblReference = new JLabel("Reference:");
		// infoPanel.add(lblReference);

		JPanel notesPanel = new JPanel();
		notesPanel.setAlignmentY(Component.BOTTOM_ALIGNMENT);
		notesPanel.setBorder(new TitledBorder(null, "Notes / Pronunciation / References:", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		notesPanel.setLayout(new VerticalLayout());
		infoPanel.add(notesPanel);

		notesArea = new JTextArea();
		notesPanel.add(notesArea);
		notesArea.setPreferredSize(new Dimension(150, 100));

		btnUpdateNotes = new JButton("Save Notes");
		notesPanel.add(btnUpdateNotes);
		btnUpdateNotes.setEnabled(false);
		btnUpdateNotes.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				saveNotes();
			}
		});

		JSplitPane splitPane = new JSplitPane();
		splitPane.setTopComponent(listPanel);
		splitPane.setBottomComponent(infoPanel);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		getContentPane().add(splitPane);

		// masterList.refresh(true);

		this.setVisible(true);
	}

	public void setupPopup() {
		masterList.popup.popupItems = EnumSet.of(
				BasicPopupMenu.POPUP_ITEMS.ADD,
				BasicPopupMenu.POPUP_ITEMS.EDIT,
				BasicPopupMenu.POPUP_ITEMS.COPY,
				BasicPopupMenu.POPUP_ITEMS.READ_ALOUD,
				BasicPopupMenu.POPUP_ITEMS.SPELL_ALOUD,
				BasicPopupMenu.POPUP_ITEMS.DELETE
				);
		masterList.setupPopup();
	}

	public void saveNotes() {
		if (!masterList.getSelectionModel().isSelectionEmpty()) {
			String notes = notesArea.getText();
			int row = masterList.getSelectedIndex();
			int id;
			if (row > -1) {
				String note = (String) masterList.getModel().getElementAt(row);
				id = GFXSQL.getInt("preApproval", "idPreApproval", "entry = '" + note + "'")[0];
				GFXSQL.alterString("preApproval", "notes", notes, id);
			}
		}
	}

	/*
	 * public class SearchTypeListener implements DocumentListener {
	 * @Override
	 * public void changedUpdate(DocumentEvent arg0) {
	 * // Trace.info("------------------------------------------------ changed notes!!!!!!!!!!!!!!!!!!!!!!!!");
	 * }
	 * @Override
	 * public void insertUpdate(DocumentEvent arg0) {
	 * update(arg0);
	 * }
	 * @Override
	 * public void removeUpdate(DocumentEvent arg0) {
	 * update(arg0);
	 * }
	 * public void update(DocumentEvent arg0) {
	 * Soundex soundex = new Soundex();
	 * int maxMatch = 0;
	 * // EditableOneColumnTableModel model = (EditableOneColumnTableModel) masterList.getModel();
	 * // masterList.getSelectionModel().clearSelection();
	 * for (int i = 0; i < model.getRowCount(); i++) {
	 * try {
	 * int difference = soundex.difference(textField.getText(), (String) model.getValueAt(i, 0));
	 * if (difference >= maxMatch && difference >= 3) {
	 * // masterList.getSelectionModel().setSelectionInterval(i, i);
	 * maxMatch = difference;
	 * }
	 * } catch (EncoderException e) {
	 * e.printStackTrace();
	 * }
	 * }
	 * }
	 * }
	 */
	public class MasterListSelectionListener implements ListSelectionListener {

		@Override
		public void valueChanged(ListSelectionEvent e) {
			ListSelectionModel lsm = (ListSelectionModel) e.getSource();
			if (!lsm.isSelectionEmpty()) {
				// int row = masterList.getSelectedRow();
				int col = 0;
				// try {
				// String entry = ((IndexedSQL<String>) masterList.getValueAt(row, col)).getElement();
				// ResultSet resultSet = GFXSQL.getResultSetFromActiveDB("preApproval", "*", "entry = '" + entry + "'");
				// while (resultSet.next()) {
				// lblResearcher.setText("Researcher:  " + Users.allUsers.get(resultSet.getInt("idPerson")).fullName());
				// lblDateApproved.setText("DateApproved:  " + new SQLDate(resultSet.getLong("date")).toString());
				// lblReference.setText("Researcher:  " + Users.allUsers.get(resultSet.getInt("idPerson")).fullName());
				// notesArea.setText(resultSet.getString("notes"));
				// }
				// } catch (SQLException e1) {
				// e1.printStackTrace();
				// }
				btnUpdateNotes.setEnabled(true);
			} else {
				btnUpdateNotes.setEnabled(false);
				// lblResearcher.setText("Researcher:  ");
				// lblDateApproved.setText("DateApproved:  ");
				// lblReference.setText("Researcher:  " + Users.allUsers.get(resultSet.getInt("idPerson")).fullName());
				notesArea.setText("");
			}
		}
	}

	public void addEntry() {
		PreApprovedText newText = new PreApprovedText();
		newText.setEntry(textField.getText());
		newText.toSQL();

		masterList.refresh(true);
	}

	public class PrintClickListener implements MouseListener {

		@Override
		public void mouseClicked(MouseEvent arg0) {
			PrintGrfxOrder printer;
			printer = new PrintGrfxOrder();

			String[] header = { "PreApproved Names:" };
			// String[] body = new String[masterList.getRowCount()];

			// for (int i = 0; i < masterList.getRowCount(); i++) {
			// body[i] = (String) masterList.getValueAt(i, 0);
			// }

			// try {
			// boolean didit = printer.doPrint(header, body, true);
			// } catch (PrinterException e) {
			// e.printStackTrace();
			// }
		}

		@Override
		public void mouseEntered(MouseEvent arg0) {
		}

		@Override
		public void mouseExited(MouseEvent arg0) {
		}

		@Override
		public void mousePressed(MouseEvent arg0) {
		}

		@Override
		public void mouseReleased(MouseEvent arg0) {
		}

	}

	public class PreApprovedAutoCompleteDocument extends AutoCompleteDocument {
		public PreApprovedAutoCompleteDocument(AbstractAutoCompleteAdaptor adaptor, boolean strictMatching) {
			super(adaptor, strictMatching);
		}
	}

	public class PreApprovedAutoCompleteAdaptor extends AbstractAutoCompleteAdaptor {
		/**
		 * a <tt>List</tt> containing the strings to be used for automatic
		 * completion
		 */
		List<?>			items;
		/** the text component that is used for automatic completion */
		JTextComponent	textComponent;
		/** the item that is currently selected */
		Object			selectedItem;

		/**
		 * Creates a new <tt>TextComponentAdaptor</tt> for the given list and text
		 * component.
		 * 
		 * @param items
		 *            a <tt>List</tt> that contains the items that are used for
		 *            automatic completion
		 * @param textComponent
		 *            the text component that will be used automatic
		 *            completion
		 */
		public PreApprovedAutoCompleteAdaptor(JTextComponent textComponent, List<?> items) {
			this.items = items;
			this.textComponent = textComponent;
		}

		@Override
		public Object getSelectedItem() {
			return selectedItem;
		}

		/*
		 * @Override
		 * public Object getSelectedItem() {
		 * String[] words = ((JTextComponent)selectedItem).getText().split("\\s");
		 * return words[words.length - 1];
		 * }
		 */
		@Override
		public int getItemCount() {
			return items.size();
		}

		@Override
		public Object getItem(int index) {
			return items.get(index);
		}

		@Override
		public void setSelectedItem(Object item) {
			selectedItem = item;
		}

		@Override
		public JTextComponent getTextComponent() {
			return textComponent;
		}
	}
}
